/*
 * WSNView.java
 */
package wsn;

import bio.Bio;
import cocma.Cocma;
import cocma.CocmaImproved;
import helper.Config;
import helper.CopyFile;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import jxl.read.biff.BiffException;
import jxl.write.WriteException;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.List;
import javax.naming.spi.DirectoryManager;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import network.DirectCommunication;
import network.Leach;
import network.Network;
import network.NetworkController;
import network.NetworkInfo;
import noneAlg.NoneAlgorithm;
import schedulingScheme.Alg;
import schedulingScheme.EventListener;
import schedulingScheme.POI;
import schedulingScheme.SensorNode;
import schedulingScheme.SensorsController;
import schedulingScheme.Stats;

/**
 * The application's main frame.
 */
public class WSNView extends FrameView implements EventListener {

    public WSNView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = WSNApp.getApplication().getMainFrame();
            aboutBox = new WSNAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        WSNApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        sensorMap = new SensorMap();
        playButton = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        stopButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        leachRadioButton = new javax.swing.JRadioButton();
        dCommunicationRadioButton = new javax.swing.JRadioButton();
        jLabel2 = new javax.swing.JLabel();
        comcaRadioButton = new javax.swing.JRadioButton();
        bioInspRadioButton = new javax.swing.JRadioButton();
        jLabel3 = new javax.swing.JLabel();
        noOfPoiTextField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        percentOfPoiTextField = new javax.swing.JTextField();
        noOfActiveSensors = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        timeTextField = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        noneRadioButton = new javax.swing.JRadioButton();
        cocmaImprovedRadioButton = new javax.swing.JRadioButton();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();
        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();

        mainPanel.setName("mainPanel"); // NOI18N

        sensorMap.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        sensorMap.setName("sensorMap"); // NOI18N
        sensorMap.setPreferredSize(new java.awt.Dimension(442, 442));

        javax.swing.GroupLayout sensorMapLayout = new javax.swing.GroupLayout(sensorMap);
        sensorMap.setLayout(sensorMapLayout);
        sensorMapLayout.setHorizontalGroup(
            sensorMapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 438, Short.MAX_VALUE)
        );
        sensorMapLayout.setVerticalGroup(
            sensorMapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 369, Short.MAX_VALUE)
        );

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(wsn.WSNApp.class).getContext().getResourceMap(WSNView.class);
        playButton.setText(resourceMap.getString("playButton.text")); // NOI18N
        playButton.setName("playButton"); // NOI18N
        playButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                playButtonActionPerformed(evt);
            }
        });

        jButton5.setText(resourceMap.getString("jButton5.text")); // NOI18N
        jButton5.setName("jButton5"); // NOI18N
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jButton6.setText(resourceMap.getString("jButton6.text")); // NOI18N
        jButton6.setName("jButton6"); // NOI18N
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        stopButton.setText(resourceMap.getString("stopButton.text")); // NOI18N
        stopButton.setName("stopButton"); // NOI18N
        stopButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stopButtonActionPerformed(evt);
            }
        });

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        leachRadioButton.setSelected(true);
        leachRadioButton.setText(resourceMap.getString("leachRadioButton.text")); // NOI18N
        leachRadioButton.setName("leachRadioButton"); // NOI18N

        dCommunicationRadioButton.setText(resourceMap.getString("dCommunicationRadioButton.text")); // NOI18N
        dCommunicationRadioButton.setName("dCommunicationRadioButton"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        comcaRadioButton.setSelected(true);
        comcaRadioButton.setText(resourceMap.getString("comcaRadioButton.text")); // NOI18N
        comcaRadioButton.setName("comcaRadioButton"); // NOI18N

        bioInspRadioButton.setText(resourceMap.getString("bioInspRadioButton.text")); // NOI18N
        bioInspRadioButton.setName("bioInspRadioButton"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        noOfPoiTextField.setEditable(false);
        noOfPoiTextField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        noOfPoiTextField.setText(resourceMap.getString("noOfPoiTextField.text")); // NOI18N
        noOfPoiTextField.setName("noOfPoiTextField"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        percentOfPoiTextField.setEditable(false);
        percentOfPoiTextField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        percentOfPoiTextField.setText(resourceMap.getString("percentOfPoiTextField.text")); // NOI18N
        percentOfPoiTextField.setName("percentOfPoiTextField"); // NOI18N

        noOfActiveSensors.setEditable(false);
        noOfActiveSensors.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        noOfActiveSensors.setText(resourceMap.getString("noOfActiveSensors.text")); // NOI18N
        noOfActiveSensors.setName("noOfActiveSensors"); // NOI18N

        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N

        timeTextField.setEditable(false);
        timeTextField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        timeTextField.setText(resourceMap.getString("timeTextField.text")); // NOI18N
        timeTextField.setName("timeTextField"); // NOI18N

        jLabel8.setText(resourceMap.getString("jLabel8.text")); // NOI18N
        jLabel8.setName("jLabel8"); // NOI18N

        noneRadioButton.setText(resourceMap.getString("noneRadioButton.text")); // NOI18N
        noneRadioButton.setName("noneRadioButton"); // NOI18N

        cocmaImprovedRadioButton.setText(resourceMap.getString("cocmaImprovedRadioButton.text")); // NOI18N
        cocmaImprovedRadioButton.setName("cocmaImprovedRadioButton"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(playButton, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel7)
                        .addGap(23, 23, 23)
                        .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(stopButton, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(sensorMap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(comcaRadioButton)
                    .addComponent(bioInspRadioButton)
                    .addComponent(cocmaImprovedRadioButton)
                    .addComponent(noneRadioButton)
                    .addComponent(jLabel1)
                    .addComponent(leachRadioButton)
                    .addComponent(dCommunicationRadioButton)
                    .addComponent(jLabel3)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(timeTextField, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(noOfActiveSensors, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(percentOfPoiTextField, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(noOfPoiTextField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel8)
                            .addComponent(jLabel6)
                            .addComponent(jLabel5)
                            .addComponent(jLabel4))))
                .addContainerGap(16, Short.MAX_VALUE))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(sensorMap, javax.swing.GroupLayout.PREFERRED_SIZE, 373, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(comcaRadioButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bioInspRadioButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cocmaImprovedRadioButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(noneRadioButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(leachRadioButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dCommunicationRadioButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(noOfPoiTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(percentOfPoiTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(noOfActiveSensors, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(timeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel8))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(playButton, javax.swing.GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE)
                            .addComponent(jButton6, javax.swing.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE)
                            .addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE)
                            .addComponent(jLabel7))
                        .addGap(16, 16, 16))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(stopButton, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );

        ((SensorMap) sensorMap).setPoiList(Alg.generatePOIs());
        ((SensorMap) sensorMap).setSensorList(Alg.generateSensors());

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(wsn.WSNApp.class).getContext().getActionMap(WSNView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 634, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 464, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        buttonGroup1.add(leachRadioButton);
        buttonGroup1.add(dCommunicationRadioButton);

        buttonGroup2.add(comcaRadioButton);
        buttonGroup2.add(bioInspRadioButton);
        buttonGroup2.add(noneRadioButton);
        buttonGroup2.add(cocmaImprovedRadioButton);

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void playButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_playButtonActionPerformed



        Thread t = new Thread() {

            @Override
            public void run() {
                super.run();

                List pois = ((SensorMap) sensorMap).getPoiList();
                List sensors = ((SensorMap) sensorMap).getSensorList();

                Network n = null;
                SensorsController sc = null;
                if (leachRadioButton.isSelected()) {
                    n = new Leach();

                }
                else {
                    n = new DirectCommunication();
                }

                if (comcaRadioButton.isSelected()) {
                    sc = new Cocma(sensors, pois);
                }
                else if (bioInspRadioButton.isSelected()){
                    sc = new Bio(sensors, pois, 1, 4);
                }
                else if (cocmaImprovedRadioButton.isSelected()){
                    sc = new CocmaImproved(sensors, pois);
                }
                else if(noneRadioButton.isSelected()){
                    sc = new NoneAlgorithm(sensors);
                }

                NetworkInfo ni = n.getNetworkInfo();
                ((SensorMap) sensorMap).setNetworkInfo(ni);


                NetworkController nc = new NetworkController(sensors, pois, n, sc);
                nc.addEventListener(WSNView.this);
                stats = new Stats(ni, pois, sensors);
                nc.start();
                try {
                    String name = getDirName() + getFileName();
                    assert(new File(Config.getResultFolder() + getDirName()).mkdir());
                    stats.saveStats(Config.getResultFolder() + name +".xls");
                    CopyFile.copyFile(new File(WSNView.class.getClassLoader().getResource("properties.properties").toURI()), new File(Config.getResultFolder() + name + ".properties"));

                } catch (URISyntaxException ex) {
                    Logger.getLogger(WSNView.class.getName()).log(Level.SEVERE, null, ex);
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(WSNView.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(WSNView.class.getName()).log(Level.SEVERE, null, ex);
                } catch (BiffException ex) {
                    Logger.getLogger(WSNView.class.getName()).log(Level.SEVERE, null, ex);
                } catch (WriteException ex) {
                    Logger.getLogger(WSNView.class.getName()).log(Level.SEVERE, null, ex);
                }
                
            }
        };
        t.start();




    }//GEN-LAST:event_playButtonActionPerformed

    private String getDirName(){
         StringBuilder sb = new StringBuilder();
        Calendar c = new GregorianCalendar();
        sb.append(c.getTime().toString().replaceAll(":", "."));
        sb.append("/");
        return sb.toString();
    }

    private String getFileName() {
       StringBuilder sb = new StringBuilder();

        sb.append("a=");
        if (comcaRadioButton.isSelected()) {
            sb.append("cocma");
        } else if (bioInspRadioButton.isSelected()) {
            sb.append("bio");
        } else if (cocmaImprovedRadioButton.isSelected()){
            sb.append("cocmaImproved");
        }
        else if (noneRadioButton.isSelected()) {
            sb.append("none");
        }
        sb.append(" n=");
        if (leachRadioButton.isSelected()) {
            sb.append("leach");

        } else {
            sb.append("direct");
        }
        return sb.toString();



    }
    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        // TODO add your handling code here:
        timesFaster = timesFaster.multiply(new BigDecimal(2));
        jLabel7.setText("x" + timesFaster.toPlainString());
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        timesFaster = timesFaster.divide(new BigDecimal(2));
        jLabel7.setText("x" + timesFaster.toPlainString());
    }//GEN-LAST:event_jButton5ActionPerformed

    private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopButtonActionPerformed
        // TODO add your handling code here:
        List<SensorNode> sensors = ((SensorMap) sensorMap).getSensorList();
        List<SensorNode> newSensors = new ArrayList<SensorNode>();
        for (SensorNode s: sensors){
            newSensors.add(new SensorNode(s.getX(), s.getY(), s.getR(), Config.getBattery() ));
        }
        ((SensorMap) sensorMap).setSensorList(newSensors);
        lastEventMillis = System.currentTimeMillis();
    lastEventTime = 0;
//        updateGUI(0);
        
    }//GEN-LAST:event_stopButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JRadioButton bioInspRadioButton;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JRadioButton cocmaImprovedRadioButton;
    private javax.swing.JRadioButton comcaRadioButton;
    private javax.swing.JRadioButton dCommunicationRadioButton;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JRadioButton leachRadioButton;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JTextField noOfActiveSensors;
    private javax.swing.JTextField noOfPoiTextField;
    private javax.swing.JRadioButton noneRadioButton;
    private javax.swing.JTextField percentOfPoiTextField;
    private javax.swing.JButton playButton;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JPanel sensorMap;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JButton stopButton;
    private javax.swing.JTextField timeTextField;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    BigDecimal timesFaster = new BigDecimal("8.0");
    private JDialog aboutBox;
    private Stats stats;

    private void updateStats(int time) {
        stats.update(time);
        Collection<POI> mPois = stats.getMonitoredPOIs();
        noOfPoiTextField.setText("" + mPois.size());
        noOfPoiTextField.repaint();
        BigDecimal percent = new BigDecimal(mPois.size() * 100).divide(new BigDecimal(((SensorMap) sensorMap).getPoiList().size()), 0, RoundingMode.HALF_UP);
        percentOfPoiTextField.setText("" + percent.toPlainString());
        percentOfPoiTextField.repaint();
        noOfActiveSensors.setText("" + stats.getActiveSensors().size());
        timeTextField.setText("" + time);

    }
    long lastEventMillis = System.currentTimeMillis();
    int lastEventTime = 0;

    private void updateGUI(int time) {
        try {
            long sleepTime = 1000 * (time - lastEventTime) - (System.currentTimeMillis() - lastEventMillis);
            sleepTime = (long) (sleepTime / timesFaster.doubleValue());
            if (sleepTime > 0) {
                Thread.sleep(sleepTime);
            }
            lastEventMillis = System.currentTimeMillis();
            lastEventTime = time;
//            sensorMap.repaint();
            SwingUtilities.invokeAndWait(new Runnable() {

                public void run() {
                    sensorMap.repaint();
                }
            });
        } catch (InvocationTargetException ex) {
            Logger.getLogger(WSNView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(WSNView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void networkReorganizedPerformed(int round, int time) {
        System.out.println("network reorganized, time =" + time);
        updateStats(time);// to nie zmienia statystyk
        updateGUI(time);
        
    }

    @Override
    public void diedSensorActionPerformed(SensorNode diedSensor, Collection<SensorNode> awakenSensors, int time) {
        System.out.println(diedSensor + " died, time = " + time);
        System.out.print("It is replaced by:");
        for (SensorNode s : awakenSensors) {
            System.out.print(s + ", ");
        }
        System.out.println("");

        updateStats(time);
        updateGUI(time);
        
    }

    @Override
    public void networkReorganizedPerformed(int time) {
                System.out.println("network reorganized, time =" + time);
                updateStats(time);
        updateGUI(time);
        
    }
}
